<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="46%" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree v-model:value="model[field]" :treeData="treeData" :fieldNames="{ title: 'menuName', key: 'menuId' }"
          checkable toolbar title="菜单分配" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './role.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { BasicTree, TreeItem } from '@/components/Tree';

import { getMenuTreeList, roleDetail, saveRole } from '@/api/demo/system';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const id = ref("")

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  if (unref(treeData).length === 0) {
    treeData.value = (await getMenuTreeList({ status: 1 })).data as any as TreeItem[];
    //console.log("---treeData.value:", treeData.value);
  }
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  if (unref(isUpdate)) {
    roleDetail(data.record).then((res) => {
      //console.log("---roleDetail:", res);
      if (res.code == 200) {
        id.value = res.data.id;
        res.data.menu = [];
        if (res.data.menuIds) {
          res.data.menu = res.data.menuIds.split(",");
        }
        setFieldsValue({
          ...res.data,
        });
      }
    });

  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    // TODO custom api
    if (values.menu) {
      values.menuIds = values.menu.join(",");
    }
    values.id = id.value;
    saveRole(values).then((res) => {
      //console.log("---saveRole:", res);
      if (res.code == 200) {
        closeDrawer();
        emit('success');
      }
    });

  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
